<?php
namespace app\api\controller;
use think\Controller;
use think\Db;

class  Dxhuidiao extends Base  {
    private $config=array(
        'APPID'              => 'wx0280081f100b9265',
        'MCHID'              => '1537296311',
        'KEY'                => 'FwS6OzDIcTZd1q10oExFwSZr6ScKysO0',
        'KEYFWS'                => 'ykIaqVCiOW44kcYfIi6VxflcNlaDKCG5',
        'APPSECRET'          => '93121d5eba0d227aec238cfcd8ae7835',
        'NOTIFY_URL'         => 'http://csdl.jintianjifen.cn/api/Weixin/huidiao',

    );
    private static $PRIVATE_KEY ='-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAILcG3bJ2l1/lU5K
TN6/wCQv0mnj1d19ffOK3g92Ip9p8IuqTl4oTC/67ciJ31O21Ru8gCg8s0CCkS2o
zyNtFK2ngM0ChFqab29SKBc+xbGBhaZ2+YIhSpVbjMVfA7ffRQR85jgt4gpcDbtv
FXj4KlEiHbfumVyqSO5KoPY0tAt1AgMBAAECgYAqZQTAx0RnZh4I7ylYQOcO0i9o
/tcamr1jWWn3uF4fJ0M2/EXHW2bTZIgEoCYqCOGhyr/6STAJhkNid34kDALWg248
2BzVuP9dnt6nPR0hJTEkGoOO24k+yQLX2rtoYoEq7cBtZZMlxGDbKTzwb6MtlZ8/
g0fY2h+Dhi6EO12YAQJBAPiFkib1UIeEUP2BdoLxsL+bD2oXUVPELrGUNieC+7ZE
8kRTeMT3AcQW08R92esim0n6FGu2Aj5F3smAnzJNgSECQQCGzCeur3mzv9NOtyUg
F4tvtNjjHwoJngFbDGtdFQzTCY4WGOIP+iMgFWQrK3izqpCywGr00BuzSkZquTJt
1TvVAkBVXBt9Ahls0oe26va3tygMR8gdmnC2otWe7NdE7vph+oBz82+xx1116plG
DiwBVVudJyZIcLWIihshfuovLuvBAkBq3a3UIs/Ufo7SyAXJ1IC6FeEg5rm5eCfQ
/B6eFBMvuFKKGD4YtpFkXTElvHgb0GyZGk1xOw/K62a6M4rUYonlAkEA6FYBIdj5
zEkr6YYsShx15frEhf8yAjegJgrvZUPWHDGWs6lQmveDuIu3rkKOSgfVssghiABK
6NxE8U/eIKoPOA==
-----END PRIVATE KEY-----';
    private static $PUBLIC_KEY  ='-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCiYHZyQ6JGGFJiM3yQCKquxVs9
KCIBfnooLjiMg9ZLsnMk0ChRWV1bKhzJuMVdCdsfVxEhn0D2ydXDwxWhQA6PMCVg
G77WSifodUSwKp/Rcvj4aeDO1gUbHOYg7HseEV9/zIUrhXCZRpGPfQyPjfZ7yI9f
dI1GcTQ6dXl5tBc7zQIDAQAB
-----END PUBLIC KEY-----';
    /**
     * 获取私钥
     * @return bool|resource
     */
    private static function getPrivateKey()
    {
        $privKey = self::$PRIVATE_KEY;
        return openssl_pkey_get_private($privKey);
    }
    /**
     * 获取公钥
     * @return bool|resource
     */
    private static function getPublicKey()
    {

        $publicKey = self::$PUBLIC_KEY;
        return openssl_pkey_get_public($publicKey);
    }
    /**
     * 创建签名
     * @param string $data 数据
     * @return null|string
     */
    public function createSign($data = '')
    {
        //  var_dump(self::getPrivateKey());die;
        if (!is_string($data)) {
            return null;
        }
        return openssl_sign($data, $sign, self::getPrivateKey(),OPENSSL_ALGO_SHA256 ) ? base64_encode($sign) : null;
    }

    /**
     * 验证签名
     * @param string $data 数据
     * @param string $sign 签名
     * @return bool
     */
    public function verifySign($data = '', $sign = '')
    {
        if (!is_string($sign) || !is_string($sign)) {
            return false;
        }
        return (bool)openssl_verify(
            $data,
            base64_decode($sign),
            self::getPublicKey(),
            OPENSSL_ALGO_SHA1
        );
    }
    /**
     * 数组转字符串
     * @param string $data 数据
     * @param string $sign 签名
     * @return bool
     */
    public function arrayToStr($data)
    {
        $datastr = '';
        foreach ($data as $k=>$v){
            if($v == null) $v = 'null';
            $datastr .= $k . '=' . $v . '&';
        }
        $datastr = trim($datastr,'&');
        return $datastr;
    }
    public function huidiao1(){
        // 获取xml
        $xml=json_encode(input());
        $arr = json_decode($xml,true);
        $strSign = $arr['sign'];      //生成签名
        unset($arr['sign']);
        $datastr = $this->arrayToStr($arr);
        $is_ok = $this->verifySign($datastr, $strSign); //验证签名
        if ($is_ok) {
            $num = $arr['outTradeNo'];
            $record = Db::name('record')->where(['record_number'=>$num])->find();
            if($record['record_status'] == 1){
                Db::startTrans ();
                try{
                    $shop = Db::name('shop')->where(['shop_id'=>$record['record_shop_id']])->find();
                    $rate = Db::name('jifen_conf')->where('conf_id',1)->value ('conf_rate');

                    $time = $arr['tradeFinishedDate'];
                    $b = new Base();
                    $money = $record['record_money'];
                    $yajin = 0;
                    if($record['record_give_jifen'] > 0){
                        $yajin = $record['record_give_jifen']*$rate;
//                    Db::name('shop')->where(['shop_id'=>$record['record_shop_id']])->dec('shop_integral',$record['record_give_jifen'])->dec('shop_pledge_money',$record['record_give_jifen']*$rate)->update();
                        try{
                            Db::name('admin')->where('area',$shop['shop_qu_id'])->setDec('integral',$record['record_give_jifen']);
                            $b->jifenFlow($record['record_give_jifen'],$shop['shop_qu_id'],$record['record_user_id'],"QRcodePay");
                        }catch (\Exception $e){

                        }
//                    Db::name('jifen_consume')->insert(['consume_content'=>'扫码支付给“'.$shop['shop_name'].'”赠送'.$record['record_give_jifen'].'积分','consume_user_id'=>$record['record_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                        Db::name('order')->insert(['o_type'=>5,'o_order_num'=>$this->getOrderNumber (),'o_money'=>$record['record_give_jifen']*$rate,'o_jifen'=>'','o_status'=>5,'o_pay_status'=>2,'o_shop_id'=>$record['record_shop_id'],'o_add_time'=>date('Y-m-d H:i:s')]);
                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'扫码支付','n_content'=>'扫码支付赠送'.$record['record_give_jifen'].'积分','n_images'=>'','n_type'=>2,'n_user_id'=>$record['record_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                        try{
                            $this->jpushUser(1,$record['record_user_id'],'扫码支付赠送'.$record['record_give_jifen'].'积分',json([]));
                            $this->jpushShop(1,$record['record_shop_id'],"收款{$money}元",['type'=>1,'money'=>$money,'type2' => 1024,'msg' => "支分宝到账{$money}元，送出{$record['record_give_jifen']}积分"]);
                        }catch (\Exception $e){

                        }
                        // 店铺现金交易1‰分红，只有送积分才送
                        $shop_user_id   = DB::name('shop')
                            ->where('shop_id',$shop['shop_id'])
                            ->value('shop_user_id');
                        $this->shop_profit($shop['shop_id'],$shop_user_id,$money,3);
                    }else{
                        try{
                            $this->jpushShop(1,$record['record_shop_id'],"收款{$money}元",['type'=>1,'money'=>$money,'type2' => 1024,'msg' => "支分宝到账{$money}元，没有送出积分"]);
                        }catch (\Exception $e){

                        }
                    }
                    Db::name('jifen_consume')
                        ->insert ([
                            'consume_content'=>'扫码支付给“'.$shop['shop_name'].'”'.$money.'元，赠送'.$record['record_give_jifen'].'积分',
                            'consume_user_id'=>$record['record_user_id'],
                            'consume_add_time'=>date("Y-m-d H:i:s")
                        ]);
                    Db::name('record')
                        ->where(['record_id'=>$record['record_id']])
                        ->update([
                            'record_third_number' => $arr['tradeNo'],
                            'record_status'=>2,
                            'record_pay_time'=>$time,
                            'record_shop_balance'=>$shop['shop_balance']+$money-$yajin,
                            'record_fen_money'=>$yajin
                        ]);
                    if($record['record_fws'] == 1){
                        Db::name('shop')
                            ->where('shop_id',$shop['shop_id'])
                            ->setInc ('shop_balance',$money-$yajin);
                    }

                    // 店铺现金成交额
                    Db::name('shop')
                        ->where('shop_id',$shop['shop_id'])
                        ->inc('shop_money_balance',$money-$yajin)
                        ->inc('shop_all_balance',$money-$yajin)
                        ->inc('shop_today_balance',$money-$yajin)
                        ->update();
                    // 店铺当日现金交易额// 定时任务，每日0点清空
//                DB::name('shop')->where('shop_id',$shop['shop_id'])->setInc ('shop_today_balance',$money-$yajin);
                    //-----------------------红包改状态---------------------
                    if($record['record_ru_id'] > 0){
                        Db::name('m_red_user')
                            ->where('ru_id',$record['record_ru_id'])
                            ->update([
                                'ru_status' => 2
                            ]);
                        //---------------------发红包-----------------------
                        try{
                            $hbData = Db::name('m_red_user')->where('ru_id',$record['record_ru_id'])
                                ->field('ru_money,ru_red_id')->find();
                            $hbmoney = $hbData['ru_money'];
                            if($hbmoney >= 0.3){
                                $openid = Db::name('u_user')->where('user_id',$record['record_user_id'])->value('user_m_h5_wx');
                                $wishing = Db::name('m_red')->where('red_id',$hbData['ru_red_id'])->value('red_title');
                                $this->hongbao2('red'.$record['record_number'],$openid,$hbmoney,$wishing);
                            }
                        }catch (\Exception $e){}
                    }
                    Db::commit ();
                    //------------------------语音设备播报-----------------
                    try{
                        $this->sayMyName($record['record_shop_id'],$money,$record['record_give_jifen'],$num);
                    }catch (\Exception $e){}
                }catch(\Exception $e){
                    Db::rollback ();
                }
            }
            $result = true;
        }else{
            $result = false;
        }
        ob_clean();
        if (!empty($result)) {
            return  json_encode(["success" => true,"result" => [
                'statusCode' => 200,
                'outTradeNo' => $arr['outTradeNo'],
                'tradeNo' => $arr['tradeNo'],
                'errorCode' => '',
                'errorMsg' => '',
            ]]);
        }else{
            return false;
        }
    }
    public function huidiao2(){
        // 获取xml
        $xml=json_encode(input());
        $arr = json_decode($xml,true);
        $strSign = $arr['sign'];      //生成签名
        unset($arr['sign']);
        $datastr = $this->arrayToStr($arr);
        $is_ok = $this->verifySign($datastr, $strSign); //验证签名
        if ($is_ok) {
            $num = $arr['outTradeNo'];
            $record = Db::name('record')->where(['record_number'=>$num])->find();
            if($record['record_status'] == 1){
                Db::startTrans ();
                try{
                    $shop = Db::name('shop')->where(['shop_id'=>$record['record_shop_id']])->find();
                    $rate = Db::name('jifen_conf')->where('conf_id',1)->value ('conf_rate');

                    $time = $arr['tradeFinishedDate'];
                    $b = new Base();
                    $money = $record['record_money'];
                    $yajin = 0;
                    if($record['record_give_jifen'] > 0){
                        $yajin = $record['record_give_jifen']*$rate;
//                    Db::name('shop')->where(['shop_id'=>$record['record_shop_id']])->dec('shop_integral',$record['record_give_jifen'])->dec('shop_pledge_money',$record['record_give_jifen']*$rate)->update();
                        try{
                            Db::name('admin')->where('area',$shop['shop_qu_id'])->setDec('integral',$record['record_give_jifen']);
                            $b->jifenFlow($record['record_give_jifen'],$shop['shop_qu_id'],$record['record_user_id'],"QRcodePay");
                        }catch (\Exception $e){

                        }
//                    Db::name('jifen_consume')->insert(['consume_content'=>'扫码支付给“'.$shop['shop_name'].'”赠送'.$record['record_give_jifen'].'积分','consume_user_id'=>$record['record_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                        Db::name('order')->insert(['o_type'=>5,'o_order_num'=>$this->getOrderNumber (),'o_money'=>$record['record_give_jifen']*$rate,'o_jifen'=>'','o_status'=>5,'o_pay_status'=>2,'o_shop_id'=>$record['record_shop_id'],'o_add_time'=>date('Y-m-d H:i:s')]);
                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'扫码支付','n_content'=>'扫码支付赠送'.$record['record_give_jifen'].'积分','n_images'=>'','n_type'=>2,'n_user_id'=>$record['record_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                        try{
                            $this->jpushUser(1,$record['record_user_id'],'扫码支付赠送'.$record['record_give_jifen'].'积分',json([]));
                            $this->jpushShop(1,$record['record_shop_id'],"收款{$money}元",['type'=>1,'money'=>$money,'type2' => 1024,'msg' => "支分宝到账{$money}元，送出{$record['record_give_jifen']}积分"]);
                        }catch (\Exception $e){

                        }
                        // 店铺现金交易1‰分红，只有送积分才送
                        $shop_user_id   = DB::name('shop')
                            ->where('shop_id',$shop['shop_id'])
                            ->value('shop_user_id');
                        $this->shop_profit($shop['shop_id'],$shop_user_id,$money,3);
                    }else{
                        try{
                            $this->jpushShop(1,$record['record_shop_id'],"收款{$money}元",['type'=>1,'money'=>$money,'type2' => 1024,'msg' => "支分宝到账{$money}元，没有送出积分"]);
                        }catch (\Exception $e){

                        }
                    }
                    Db::name('jifen_consume')
                        ->insert ([
                            'consume_content'=>'扫码支付给“'.$shop['shop_name'].'”'.$money.'元，赠送'.$record['record_give_jifen'].'积分',
                            'consume_user_id'=>$record['record_user_id'],
                            'consume_add_time'=>date("Y-m-d H:i:s")
                        ]);
                    Db::name('record')
                        ->where(['record_id'=>$record['record_id']])
                        ->update([
                            'record_third_number' => $arr['tradeNo'],
                            'record_status'=>2,
                            'record_pay_time'=>$time,
                            'record_shop_balance'=>$shop['shop_balance'],
                            'record_fen_money'=>$yajin
                        ]);
                    if($record['record_fws'] == 1){
                        Db::name('shop')
                            ->where('shop_id',$shop['shop_id'])
                            ->setInc ('shop_balance',$money-$yajin);
                    }

                    // 店铺现金成交额
                    Db::name('shop')
                        ->where('shop_id',$shop['shop_id'])
                        ->inc('shop_money_balance',$money-$yajin)
                        ->inc('shop_all_balance',$money-$yajin)
                        ->inc('shop_today_balance',$money-$yajin)
                        ->update();
                    // 店铺当日现金交易额// 定时任务，每日0点清空
//                DB::name('shop')->where('shop_id',$shop['shop_id'])->setInc ('shop_today_balance',$money-$yajin);
                    //-----------------------红包改状态---------------------
                    if($record['record_ru_id'] > 0){
                        Db::name('m_red_user')
                            ->where('ru_id',$record['record_ru_id'])
                            ->update([
                                'ru_status' => 2
                            ]);
                        //---------------------发红包-----------------------
                        try{
                            $hbData = Db::name('m_red_user')->where('ru_id',$record['record_ru_id'])
                                ->field('ru_money,ru_red_id')->find();
                            $hbmoney = $hbData['ru_money'];
                            if($hbmoney >= 0.3){
                                $openid = Db::name('u_user')->where('user_id',$record['record_user_id'])->value('user_m_h5_wx');
                                $wishing = Db::name('m_red')->where('red_id',$hbData['ru_red_id'])->value('red_title');
                                $this->hongbao2('red'.$record['record_number'],$openid,$hbmoney,$wishing);
                            }
                        }catch (\Exception $e){}
                    }
                    Db::commit ();
                    //------------------------语音设备播报-----------------
                    try{
                        $this->sayMyName($record['record_shop_id'],$money,$record['record_give_jifen'],$num);
                    }catch (\Exception $e){}
                }catch(\Exception $e){
                    Db::rollback ();
                }
            }
            $result = true;
        }else{
            $result = false;
        }
        ob_clean();
        if (!empty($result)) {
            return  json_encode(["success" => true,"result" => [
                'statusCode' => 200,
                'outTradeNo' => $arr['outTradeNo'],
                'tradeNo' => $arr['tradeNo'],
                'errorCode' => '',
                'errorMsg' => '',
            ]]);
        }else{
            return false;
        }
    }


    public function httpRequest($url, $postData = [])
    {
        $header[] = "Content-type: text/xml";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
        curl_setopt($ch,CURLOPT_SSLCERT,ROOT_PATH.'/public/apiclient_cert.pem');
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
        curl_setopt($ch,CURLOPT_SSLKEY,ROOT_PATH.'/public/apiclient_key.pem');
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $result = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }
        curl_close($ch);

        return $result;
    }
    

    public function makeSign($data,$signty=false){
        $data=array_filter($data);
        ksort($data);
        $string_a=http_build_query($data);
        $string_a=urldecode($string_a);
        $config=$this->config;
        if($signty == true){
            $config['KEY'] = $config['KEYFWS'];
        }
        $string_sign_temp=$string_a."&key=".$config['KEY'];
        $sign = md5($string_sign_temp);
        $result=strtoupper($sign);
        return $result;
    }


    public function toArray($xml){
        libxml_disable_entity_loader(true);
        $result= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $result;
    }
    

    public function toXml($data){
        if(!is_array($data) || count($data) <= 0){
        }
        $xml = "<xml>";
        foreach ($data as $key=>$val){
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }


    function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val))
            {
                $xml.="<".$key.">".$val."</".$key.">";

            }
            else
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
        $xml.="</xml>";
        return $xml;
    }

    public function postXmlCurl($xml,$url,$second=30)
    {
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $data = curl_exec($ch);
        if($data)
        {
            curl_close($ch);
            return $data;
        }
        else
        {
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error"."<br>";
            echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
            curl_close($ch);
            return false;
        }
    }

    function getRandChar($length){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];
        }

        return $str;
    }

    public function getOrder($prepayId){
        $data["appid"] = $this->config["APPID"];
        $data["noncestr"] = $this->getRandChar(32);
        $data["package"] = "Sign=WXPay";
        $data["partnerid"] = $this->config['MCHID'];
        $data["prepayid"] = $prepayId;
        $data["timestamp"] = time();
        $s = $this->makeSign($data, false);
        $data["sign"] = $s;
        
        return $data;
    }
    

    public  function get_client_ip()
    {
        if ($_SERVER['REMOTE_ADDR']) {
            $cip = $_SERVER['REMOTE_ADDR'];
        } elseif (getenv("REMOTE_ADDR")) {
            $cip = getenv("REMOTE_ADDR");
        } elseif (getenv("HTTP_CLIENT_IP")) {
            $cip = getenv("HTTP_CLIENT_IP");
        } else {
            $cip = "unknown";
        }
        return $cip;
    }

    public function userTiXian($refundNo,$openid,$money,$name){
        $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
        $config_data = [
            'mch_appid' => $this->config['APPID'],
            'mchid' => $this->config['MCHID'],
            'nonce_str' => $this->getRandChar(32),
            'partner_trade_no' => $refundNo,
            'openid' => $openid,
            'check_name' => "FORCE_CHECK",
            're_user_name' => $name,
            'amount' =>  $money*100,
            'desc' => '支分宝转账',
            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
        ];
        $sign = $this->makeSign($config_data);
        $config_data['sign'] = $sign;
        $xml = $this->toXml($config_data);
        $response = $this->httpRequest($url,$xml);
        $result = $this->toArray($response);
        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            return ['status'=>200,'msg'=>$result['payment_no']];
        }else if($result['return_code'] == 'FAIL'){
            return ['status'=>100,'msg'=>$result['return_msg']];
        }else{
            if($result['err_code'] == 'SENDNUM_LIMIT'){
                return ['status'=>100,'msg'=>'单个用户每天最多可提现3次'];
            }
            return ['status'=>100,'msg'=>$result['err_code_des']];
        }
    }
public function errorUpForError(){
        return 1;die;exit();
            Db::startTrans ();
            try{
                $num = '1111111111111111111111111111111111111111';
                $getInfo['attach'] = 'upPartner';
                $getInfo['total_fee'] = 100;
                $getInfo['transaction_id'] = '微信那边过来的单号';
                $info = Db::name('order')->where('o_order_num',$num)->find();
                switch($getInfo['attach']){
                    // 合伙人
                    case 'upPartner':
                        if ($info['o_pay_status'] != 2) {
                            // 付款成功添加合伙人信息
                            $temp['par_user_id'] = $info['o_user_id'];
                            $par_user_info  = DB::name('u_user')
                                ->where(['user_id'=>$info['o_user_id']])
                                ->field('user_username,user_phone,user_area,user_recommend')
                                ->find();
                            $temp['par_user_username']  = $par_user_info['user_username'];
                            $temp['par_user_phone']     = $par_user_info['user_phone'];
                            $temp['par_qu_id']          = $par_user_info['user_area'];
                            $temp['par_add_time']       = date('Y-m-d H:i:s',time());
                            $temp['par_class_id']       = $info['o_class_id'];
                            $partner_class = DB::name('partner_class')
                                ->where(['class_id'=>$info['o_class_id']])
                                ->field('class_level,class_name,class_jifen,class_tui_jifen,class_agent_money,class_head_money,class_tui_money,class_fans_days')
                                ->find();
                            $temp['par_class_level'] = $partner_class['class_level'];
                            // 如果是城市合伙人，需要后台代理商绑定
                            if ($partner_class['class_level'] != 3) {
                                $temp['par_status'] = 2;
                            }else{
                                $temp['par_status'] = 1;
                            }
                            // 是否是推荐人推荐
                            if (!empty($par_user_info['user_recommend'])) {
                                $par_parent_id = DB::name('partner')
                                    ->where(['par_user_id'=>$par_user_info['user_recommend'],'par_cancel'=>0])
                                    ->value('par_id');
                                if (!empty($par_parent_id)) {
                                    $temp['par_parent_id'] = $par_parent_id;
                                }
                            }
                            // 升级合伙人
                            if ($info['o_partner_up'] == 1) {
                                $old = DB::name('partner')
                                    ->where(['par_user_id'=>$info['o_user_id'],'par_cancel'=>0])
                                    ->find();
                                $old_id = $old['par_id'];
                                //往前推时间，减去已使用时间
                                $date1 = date("Y-m-d",strtotime ($old['par_add_time']));
                                $date2 = date ("Y-m-d");
                                $diff = (strtotime ($date2) - strtotime($date1)) / (60 * 60 * 24);

                                // 剩余粉丝天数计算
                                $oldFansDays = DB::name('partner_class')->where(['class_id'=>$old['par_class_id']])->value('class_fans_days');
                                $newFansDays = $partner_class['class_fans_days'];
                                if ($diff > $oldFansDays) {
                                    $diff = $newFansDays - $oldFansDays;
                                    $temp['par_add_time'] = date("Y-m-d H:i:s",strtotime("+{$diff} day",strtotime ($temp['par_add_time'])));
                                } else {
                                    // 还是原来的日期
                                    $temp['par_add_time'] = $old['par_add_time'];
                                }

                                $old_partner    = DB::name('partner')
                                    ->where(['par_user_id'=>$info['o_user_id'],'par_cancel'=>0])
                                    ->update(['par_cancel'=>1]);
                                if (!empty($old_partner)) {
                                    $temp['par_up'] = 1;
                                }
                            }
                            $temp['par_cancel'] = 0;
                            $partner_add = DB::name('partner')->insertGetId($temp);
                            // 判断合伙人的区代理是否存在，不存在积分由琅琊区1134出
                            $is_qu = DB::name('admin')->where('area',$temp['par_qu_id'])->find();
                            if (empty($is_qu)) {
                                $temp['par_qu_id'] = 1134;
                            }
                            if (!empty($partner_add)) {
                                // 修改用户表用户等级/付款方式
                                if ($temp['par_class_level'] == 1) {
                                    $user_level = 4;
                                }elseif ($temp['par_class_level'] == 2) {
                                    $user_level = 3;
                                }
                                // 修改用户信息
                                if (!empty($user_level)) {
                                    DB::name('u_user')->where(['user_id'=>$info['o_user_id']])->update(['user_level'=>$user_level,'user_partner_type'=>$info['o_pay_type']]);
                                }
                                // 如果是升级用户，修改所有的该用直接下级的par_parent_id
                                if ($info['o_partner_up'] == 1) {
                                    DB::name('partner')->where(['par_parent_id'=>$old_id])->update(['par_parent_id'=>$partner_add]);
                                }
                                // 付款成功奖励积分
                                $integral = $info['o_money'];// 奖励用户支付钱的积分数
                                Db::name('admin')->where('area',$temp['par_qu_id'])->setDec('integral',$integral);//代理送出积分
                                $this->jifenFlow($integral,$temp['par_qu_id'],$info['o_user_id'],"partner");
                                Db::name('jifen_consume')->insert(['consume_content'=>'您升级为'.$partner_class['class_name'].'获得'.$integral.'积分','consume_user_id'=>$info['o_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                                Db::name('notice')->insert (['n_to'=>1,'n_title'=>'成为合伙人','n_content'=>'您升级为'.$partner_class['class_name'].'支付金额'.$info['o_money'].'元','n_images'=>'','n_type'=>3,'n_user_id'=>$info['o_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                                try {
                                    $this->jpushUser(1,$info['o_user_id'],'您升级为'.$partner_class['class_name'].'支付金额'.$info['o_money'].'元',json([]));
                                } catch (\Exception $e) {}
                                // 推荐人奖励
                                if (!empty($temp['par_parent_id'])) {
                                    $parent_partner = DB::name('partner')
                                        ->where(['par_id'=>$temp['par_parent_id']])
                                        ->find();
                                    // 判断合伙人的区代理是否存在，不存在积分由琅琊区1134出
                                    $is_parent_qu = DB::name('admin')->where('area',$parent_partner['par_qu_id'])->find();
                                    if (empty($is_qu)) {
                                        $parent_partner['par_qu_id'] = 1134;
                                    }
                                    // 如果是升级合伙人，推荐人奖励要减掉原来的推荐奖励
                                    if ($info['o_partner_up'] == 1) {
                                        $form_tui = DB::name('partner_invite')
                                            ->where(['inv_be_userid'=>$info['o_user_id'],'inv_type'=>2,'inv_level'=>1,'inv_user_id'=>$parent_partner['par_user_id']])
                                            ->field('inv_id,inv_integral,inv_money')
                                            ->select();
                                        $form_jifen = 0;
                                        $form_money = 0;
                                        foreach ($form_tui as $key => $vo) {
                                            $form_jifen += $vo['inv_integral'];
                                            $form_money += $vo['inv_money'];
                                        }
                                        $partner_class['class_tui_jifen'] = $partner_class['class_tui_jifen'] - $form_jifen;
                                    }
                                    // 积分奖励
                                    Db::name('admin')->where('area',$parent_partner['par_qu_id'])->setDec('integral',$partner_class['class_tui_jifen']);//代理送出积分
                                    $this->jifenFlow($partner_class['class_tui_jifen'],$parent_partner['par_qu_id'],$parent_partner['par_user_id'],"parentPartner");
                                    // 邀请合伙人获得的积分奖励
                                    DB::name('u_user')->where(['user_id'=>$parent_partner['par_user_id']])->setInc('user_par_integral',$partner_class['class_tui_jifen']);
                                    // 添加获得积分奖励记录
                                    $arr = [
                                        'inv_user_id'   => $parent_partner['par_user_id'],
                                        'inv_par_id'    => $parent_partner['par_id'],
                                        'inv_integral'  => $partner_class['class_tui_jifen'],
                                        'inv_level'     => 1,
                                        'inv_type'      => 2,
                                        'inv_be_userid' => $info['o_user_id'],
                                        'inv_add_time'  => date('Y-m-d H:i:s',time())
                                    ];
                                    DB::name('partner_invite')->insert($arr);
                                    $str1 = '';
                                    // 事业合伙人送推荐人现金
                                    if (!empty($partner_class['class_tui_money'])) {
                                        // 如果是升级合伙人，推荐人奖励要减掉原来的推荐奖励
                                        if ($info['o_partner_up'] == 1) {
                                            $partner_class['class_tui_money'] = $partner_class['class_tui_money'] - $form_money;
                                        }
                                        // 增加现金提现额度
                                        DB::name('u_user')->where(['user_id'=>$parent_partner['par_user_id']])->setInc('user_money_balance',$partner_class['class_tui_money']);
                                        // 记录现金收益
                                        $arr = [
                                            'inv_user_id'   => $parent_partner['par_user_id'],
                                            'inv_par_id'    => $parent_partner['par_id'],
                                            'inv_money'     => $partner_class['class_tui_money'],
                                            'inv_level'     => 1,
                                            'inv_type'      => 2,
                                            'inv_be_userid' => $info['o_user_id'],
                                            'inv_add_time'  => date('Y-m-d H:i:s',time())
                                        ];
                                        DB::name('partner_invite')->insert($arr);
                                        // 邀请合伙人获得的现金奖励
                                        DB::name('u_user')->where(['user_id'=>$parent_partner['par_user_id']])->setInc('user_par_money',$partner_class['class_tui_money']);
                                        $str1 = $partner_class['class_tui_money'].'元+';
                                    }
                                    Db::name('jifen_consume')->insert(['consume_content'=>'您邀请'.$temp['par_user_username'].'成为'.$partner_class['class_name'].'获得'.$str1.$partner_class['class_tui_jifen'].'积分奖励','consume_user_id'=>$parent_partner['par_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                                    Db::name('notice')->insert (['n_to'=>1,'n_title'=>'推荐合伙人','n_content'=>'您邀请'.$temp['par_user_username'].'成为'.$partner_class['class_name'].'获得'.$str1.$partner_class['class_tui_jifen'].'积分奖励','n_images'=>'','n_type'=>3,'n_user_id'=>$parent_partner['par_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                                    // $this->jpushUser(1,$parent_partner['par_user_id'],'您邀请'.$temp['par_user_username'].'成为'.$partner_class['class_name'].'获得'.$str1.$partner_class['class_tui_jifen'].'积分奖励',json([]));
                                }
                                // 升级合伙人代理商和总部的收益要减去之前的收益
                                $area_money = DB::name('earnings')
                                    ->where(['m_area_user'=>$info['o_user_id'],'m_area_type'=>2,'m_area'=>$temp['par_qu_id']])
                                    ->sum('m_money');
                                $head_money = DB::name('earnings')
                                    ->where(['m_area_user'=>$info['o_user_id'],'m_area_type'=>1,'m_area'=>1])
                                    ->sum('m_money');
                                if (!empty($area_money)) {
                                    $partner_class['class_agent_money'] = $partner_class['class_agent_money'] - $area_money;
                                }
                                if (!empty($head_money)) {
                                    $partner_class['class_head_money'] = $partner_class['class_head_money'] - $head_money;
                                }
                                // 代理商获得奖励没有代理就总部拿
                                if (!empty($is_qu)) {
                                    DB::name('admin')->where(['area'=>$temp['par_qu_id']])->setInc('balance',$partner_class['class_agent_money']);
                                }else{
                                    DB::name('admin')->where('id',1)->setInc('balance',$partner_class['class_agent_money']);
                                }
                                // 记录现金收益
                                Db::name('earnings')->insert(['m_money'=>$partner_class['class_agent_money'],'m_area'=>$temp['par_qu_id'],'m_add_time'=>date('Y-m-d H:i:s'),'m_area_type'=>2,'m_area_user'=>$temp['par_user_id']]);
                                // 总部获得奖励
                                DB::name('admin')->where('id',1)->setInc('balance',$partner_class['class_head_money']);
                                // 记录现金收益
                                Db::name('earnings')->insert(['m_money'=>$partner_class['class_head_money'],'m_area'=>1,'m_add_time'=>date('Y-m-d H:i:s'),'m_area_type'=>1,'m_area_user'=>$temp['par_user_id']]);
                            }
                        }
                        break;
                }
                Db::name('admin')->where('id',1)->setInc ('balance',$getInfo['total_fee']/100 );
                Db::name ('order')->where ('o_order_num' , $num)->update (['o_pay_status' => 2 , 'o_third_order_num' => $getInfo['transaction_id']]);

                Db::commit ();
            }catch(\Exception $e){
                file_put_contents ( APP_PATH."api/controller/wxpay_user1_log.txt", date ( "Y-m-d H:i:s" ) . "  " . $e . "\r\n", FILE_APPEND );
                Db::rollback ();
            }
            $result = true;
        ob_clean();
       exit;
    }

    /**
     * 红包
     * @param $refundNo
     * @param $openid
     * @param $money
     * @param $name
     * @return array
     */
    public function hongbao2($refundNo,$openid,$money,$wishing){
        $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
        if(!$wishing) $wishing = '恭喜您获得随机红包';
        $config_data = [
            'wxappid' => 'wxcb63bdccb205e77b',
            'mch_id' => $this->config['MCHID'],
            'nonce_str' => $this->getRandChar(32),
            'mch_billno' => $refundNo,
            'send_name' => '支分宝',
            'scene_id' => 'PRODUCT_2',
            're_openid' => $openid,
            'total_amount' =>  $money*100,
            'total_num' => 1,
            'wishing' => $wishing,
            'client_ip' => $_SERVER['REMOTE_ADDR'],
            'act_name' => '扫码红包',
            'remark' => '扫码红包',
        ];
        $sign = $this->makeSign($config_data);
        $config_data['sign'] = $sign;
        $xml = $this->toXml($config_data);
        $response = $this->httpRequest($url,$xml);
        $result = $this->toArray($response);
        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            return ['status'=>200,'msg'=>$result['payment_no']];
        }else if($result['return_code'] == 'FAIL'){
            return ['status'=>100,'msg'=>$result['return_msg']];
        }else{
            return ['status'=>100,'msg'=>$result['err_code_des']];
        }
    }
//    原来的转账
//    public function hongbao2($refundNo,$openid,$money){
//        $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
//        $config_data = [
//            'mch_appid' => 'wxcb63bdccb205e77b',
//            'mchid' => $this->config['MCHID'],
//            'nonce_str' => $this->getRandChar(32),
//            'partner_trade_no' => $refundNo,
//            'openid' => $openid,
//            'check_name' => "NO_CHECK",
//            'amount' =>  $money*100,
//            'desc' => "支分宝付款天天领红包",
//            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
//        ];
//        $sign = $this->makeSign($config_data);
//        $config_data['sign'] = $sign;
//        $xml = $this->toXml($config_data);
//        $response = $this->httpRequest($url,$xml);
//        $result = $this->toArray($response);
//        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
//            return ['status'=>200,'msg'=>$result['payment_no']];
//        }else if($result['return_code'] == 'FAIL'){
//            return ['status'=>100,'msg'=>$result['return_msg']];
//        }else{
//            if($result['err_code'] == 'SENDNUM_LIMIT'){
//                return ['status'=>100,'msg'=>'单个用户每天最多可提现3次'];
//            }
//            return ['status'=>100,'msg'=>$result['err_code_des']];
//        }
//    }
}